home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: netcom.com!smryan
- From: smryan@netcom.com (@#$%!?!)
- Subject: Re: double-->float... number changes
- Message-ID: <smryanDq1MEJ.25B@netcom.com>
- Organization: The Programmer formerly known as S M Ryan
- X-Newsreader: TIN [version 1.2 PL1]
- References: <4l3olr$85o@news.magi.com>
- Date: Thu, 18 Apr 1996 05:39:55 GMT
- Sender: smryan@netcom12.netcom.com
-
- : I have a number (that I pick up from Sybase), declared as a double,
- : it's value is 123.4, I then want to store it in a float variable, but
- : the number changes to 123.399994.
-
- .4 cannot be exactly represented in binary, the presumed radix of any
- floating-point type, so truncating trailing bits replaces one inexact
- representation with another, even less exact, representation. At some
- point the effects are bound to be noticeable.
-
- : This messes up calculations later on in program.
- : I tried converting the number to a string and using atof() to get a
- : float number, but this function returns a double?!, and the subsequent
- : conversion to a float produces the same error.
-
- : Is there a way to get 123.4 when converting to a float number?
-
- You can round fractional digits. If you want to round x to 2 decimal
- places, one possible code is
-
- x = ((long)(x*100+.5))/100.0;
-
- There are others, perhaps already available in your friendly
- neighbourhood math library.
-
- And depending on the range of values and their operations, you can
- do it all in integers with implicit decimal points (like Cobol).
-
- --
- The Queen who loves, the Queen of life, | smryan@netcom.com PO Box 1563
- the Queen who straits, the Queen of strife;| Cupertino, California
- with gasp of death or gift of breath | (xxx)xxx-xxxx 95015
- she brings the choice of birth or knife. | I don't use no smileys
-